package com.book.backend.service.impl;

import com.book.backend.service.AiService;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class AiServiceImpl implements AiService {

    @Override
    public SseEmitter outPut(String msg) throws IOException {
       SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE);


        sseEmitter.onCompletion(() -> System.out.println("Stream completed"));
        sseEmitter.onTimeout(() -> sseEmitter.complete());
        sseEmitter.onError(ex -> sseEmitter.completeWithError(ex));

        String urlStr = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        String apiKey = "sk-ac3003f0a5304aceadb6e70a2d715052";

        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setRequestProperty("X-DashScope-SSE", "enable");
//        connection.setRequestProperty("Accept", "text/event-stream");
        connection.setDoOutput(true);

        String jsonInputString = String.format("{\"model\": \"qwen-turbo\", \"input\": {\"messages\": [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}, {\"role\": \"user\", \"content\": \"%s\"}]}, \"parameters\": {\"result_format\": \"message\",\"incremental_output\":true}}",msg);

        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.write(jsonInputString.getBytes(StandardCharsets.UTF_8));
            wr.flush();
        }

        StringBuilder response = new StringBuilder();
        String regex = "\"content\":\"(.*?)\",\"role\"";
        Pattern pattern = Pattern.compile(regex);

        ArrayList show_result = new ArrayList<>();
        System.out.println("模型生成回复：");


        new Thread(() -> {
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
                Matcher matcher = pattern.matcher(inputLine);
                show_result.add(inputLine);
                if (matcher.find()) {
                    String content = matcher.group(1);
                    if (content.contains("\\n\\n")){
                        String str = content.replaceAll("\\\\n\\\\n", "<br><br>");
                        sseEmitter.send(str);
                    }else {
                        sseEmitter.send(content);
                    }
                    System.out.print(content);
                }
            }
            sseEmitter.complete();
        }catch (Exception e) {
            sseEmitter.completeWithError(e);
        }
        }).start();
        connection.disconnect();

        return sseEmitter;
    }
}
